package com.lanhao.aot.carrierintegration.rupost;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;

public class DPXExpressUtil {
	private static final Logger LOG = LoggerFactory.getLogger(DPXExpressUtil.class);
	private static String API_USERNAME = "ceshi2222";
	private static String SALT_VALUE = "51978be65d2849abb72874982c5b9f7c6";
	private static String EXPRESS_TYPE = "PPT101";
	private static String DELIVERY_TYPE = "Courier";
	private static String ORDER_URL = "http://order.dpx-express.com/api/order/contract/create";

	public static void main(String[] args) {
		createOrder();
	}

	public static String createOrder() {
		JSONObject request = new JSONObject();
		request.put("apiUserName", API_USERNAME);
		request.put("labelType", "url");
//		request.put("taxNumber","");
//		request.put("ioss","");
		request.put("custNo", IdUtil.getSnowflakeNextIdStr());
		request.put("expressType", EXPRESS_TYPE);
		request.put("originCountryCode", "CN");
		request.put("destCountryCode", "RU");
		request.put("deliveryType", DELIVERY_TYPE);

		JSONObject sender = new JSONObject();
		sender.put("name", "Патин Александр Иванович");
		sender.put("company", "");
		sender.put("landlinePhone", "");
		sender.put("mobile", "9047817238");
		sender.put("zipcode", "603140");
		sender.put("email", "");
		sender.put("province", "Нижегородская обл");
		sender.put("city", "Нижний Новгород г");
		sender.put("district", "");
		sender.put("address", "Нижний Новгород, проспект Ленина, 19");
		request.put("sender", sender);

		JSONObject receiver = new JSONObject();
		receiver.put("name", "Энхэ Дондоков");
		receiver.put("company", "");
		receiver.put("landlinePhone", "");
		receiver.put("mobile", "79225759535");
		receiver.put("zipcode", "102961");
		receiver.put("email", "");
		receiver.put("province", "Москва");
		receiver.put("city", "Москва");
		receiver.put("district", "");
		receiver.put("address", "город Москва, улица Придорожная, дом 4, строение 32.");
		receiver.put("doorplate", "");
		request.put("receiver", receiver);

		JSONObject parcel = new JSONObject();
		parcel.put("hasLiquid", "0");
		parcel.put("hasBattery", "0");
		parcel.put("hasPowder", "0");
		parcel.put("custLength", "");
		parcel.put("custWidth", "");
		parcel.put("custHeight", "");
		parcel.put("custDeclareValue", "2.0");
		parcel.put("custDeclareCurrency", "USD");
		parcel.put("custWeight", "0.3");

		JSONArray productList = new JSONArray();
		JSONObject product = new JSONObject();
		product.put("nameCn", "安和货物");
		product.put("nameEn", "AnHeGoods");
		product.put("quantity", "1");
		product.put("unitPrice", "2.0");
		product.put("weight", "0.3");
		product.put("hsCode", "1023515264");
		product.put("pickingInfo", "87853856");
		product.put("productUrl", "https://xxxxxx/c/58a2be4c6b1eea5327ac6d00");
		product.put("sku", "商品sku描述");

		productList.add(product);

		parcel.put("productList", productList);
		request.put("parcel", parcel);

		String requestBody = request.toJSONString();
		
		Map<String, String> header = Maps.newHashMap();
		header.put("checkMd", MD5Lower(requestBody, SALT_VALUE));
		header.put("Content-Type", "application/json");
		LOG.info("url={}, header={}, request={}", ORDER_URL, header, requestBody);
		String response = HttpRequest.post(ORDER_URL).addHeaders(header).body(requestBody).execute().body();
		LOG.info("response={}", response);
		
		try {
			FileUtils.writeStringToFile(new File("DPX_Response.txt"), response, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return response;
	}

	/**
	 * 对字符串 MD5 加盐值加密
	 *
	 * @param plainText 传入要加密的字符串
	 * @param saltValue 传入要加的盐值
	 * @return MD5加密后生成32位(小写字母+数字)字符串
	 */
	public static String MD5Lower(String plainText, String saltValue) {
		try {
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest md = MessageDigest.getInstance("MD5");

			// 使用指定的字节更新摘要
			md.update(plainText.getBytes(StandardCharsets.UTF_8));
			md.update(saltValue.getBytes(StandardCharsets.UTF_8));

			// digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
			// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值。1 固定值
			byte[] digest = md.digest();
			StringBuilder result = new StringBuilder();
			for (byte b : digest) {
				String temp = Integer.toHexString(b & 0xff);
				if (temp.length() == 1) {
					temp = "0" + temp;
				}
				result.append(temp);
			}
			return result.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
}
